import router from "@/router";
import { getToken, setToken } from "@/utils/auth";
import Vue from "vue";
import Vuex from "vuex";
import { login, logout } from "@/api/index";
router;
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: getToken(),
    userInfo: {},
  },
  getters: {},
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
  },
  actions: {
    login({ commit }, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password })
          .then((response) => {
            commit("SET_TOKEN", response.data.token);

            setToken(response.data.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    logout({ commit }) {
      logout()
        .then((res) => {
          commit("SET_TOKEN", "");
          setToken("");
          router.push("/login");
        })
        .catch((_) => {});
    },
  },
  modules: {},
});
